package q;
import java.util.Scanner;
public class RSAAA {
	private long p,q,phi,e,d,n;

	public RSAAA(){
		Scanner input = new Scanner(System.in);
		System.out.println("输入第一个素数p:");
		 p = input.nextInt();
		System.out.println("请输入第二个素数q:");
		 q = input.nextInt();
		 n = p*q;
		 phi = (p-1)*(q-1);
		
				while(gcd(e,phi)!=1){
				
					 e=(long)(Math.random()*phi)+1;
				}
				
			
			  
		 d = calculateD();
		
		  }
	private long calculateD(){
		long t0 = 0,t1 = 1,t2 = -1;
	    long r0 = phi, m = r0,r1 = e,r2 = -1;
	    do{
	    	long q = r0/r1;
	    	r2 = r0-r1*q;
	    	if(r2==0)break;
	    	t2 = t0-t1*q;
	    	while(t2<0){
	    		t2+=m;
	    	}
	    	if(t2>=m){
	    		t2%=m;
	    	}
	    	r0=r1;
	    	r1=r2;
	    	t0=t1;
	    	t1=t2;
	    }while(r2!=0);
	    if(r1!=1){
	    	return 0;
	    }
	    else{
	    	return t2;
	    }
	}
	
	
	public long gcd(long a,long b){
		while(b!=0){
			long temp = a%b;
			a = b;
			b = temp;
			
		}
		return a;
	}
	    
	public long encrypt(long e,long n,long ming){
		if(n < 1 || e < 1){    
            return 0L;    
        }    
        //加密或者解密之后的数据    
        long rsaMessage = 0L;    
            
        //加密核心算法    
        rsaMessage = (long)Math.round(Math.pow(ming, e) % n);    
        return rsaMessage;    
    
	}
	
	public long deciphering(long d,long n,long mi){
		if(n < 1 || d < 1){    
            return 0L;    
        }   
        //加密或者解密之后的数据    
        long rsaMessage = 0L;    
            
        //加密核心算法    
        rsaMessage = (long)Math.round(Math.pow(mi, d) % n);    
        return rsaMessage;    
    
	}
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		RSAAA rsa = new RSAAA();
		
		System.out.println("n的值为："+rsa.n);
       System.out.println("e的值为："+rsa.e);
       System.out.println("d的值为："+rsa.d);
       System.out.println("公钥为："+rsa.e+" "+rsa.n);
       System.out.println("私钥为："+rsa.d+" "+rsa.n);
       
       System.out.print("请输入明文：");
		//final long MAXLENGTH = 500;
		//long[] clear=new long[MAXLENGTH];
		//long[] Ciphertext=new long[MAXLENGTH];
       Scanner input = new Scanner(System.in);
		long m = input.nextInt();
		long e = 7;
		long d = 23;
		
		long n = 187;
		long miWen=rsa.encrypt(e,rsa.n,m);
		long mingWen=rsa.encrypt(d,n,miWen);
		//long mingWen=rsa.deciphering(d,n,miWen);
       System.out.println("明文加密E后："+miWen);
      
       System.out.println("密文解密后："+mingWen);
       
      /* for(long i=0;i<MAXLENGTH;i++){
			clear[i]=input.nextInt();
			if(clear[i]==-1) break;
			System.out.prlongln("明文为："+clear[i]);
			
		}
       for(long j=0;j<clear.length;j++){
			Ciphertext[j]=rsa.encrypt(rsa.e,rsa.n,clear[j]);
			System.out.println("明文加密后："+Ciphertext[j]);
		}
		*/
	}
  
}
